package com.voicechat.firstmet.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.SystemAndOfficialAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.CoummunityNotice;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity
 * @ClassName: SystemAndOfficialActivity
 * @Description: 系统消息和官方通知页面
 * @Author: ljp
 * @CreateDate: 2018/11/17 13:28
 * @Version: 1.0
 */
public class SystemAndOfficialActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.recycler_list)
    RecyclerView recyclerList;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.linear_layout)
    LinearLayout linearLayout;


    private String type;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String token;
    private String id;
    private String deviceInfo;
    private List<CoummunityNotice.PageBean.ListBean> listBeans;
    private int layout;
    private SystemAndOfficialAdapter systemAndOfficialAdapter;
    private int page;
    private String TAG = "SystemAndOfficialActivity";

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_system_official;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        type = getIntent().getStringExtra("type");//对方的id
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        id = mySeleInfo.getId();
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        initView();
    }

    private void initView() {
        page = 1;
        listBeans = new ArrayList<>();
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                setHttpData();
                smartRefresh.finishRefresh(10000);//如果网络不好10秒完成加载标识
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                setHttpData();
                smartRefresh.finishLoadMore(10000);//如果网络不好10秒完成加载标识
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        if (type.equals("Official")) {//官方通知
            tvTitle.setText("官方通知");
            layout = R.layout.item_official_message;
        } else {
            tvTitle.setText("系统消息");
            layout = R.layout.item_system_message;
            Log.i(TAG, "initView: ------系统消息----");
            setHttpRead();
        }
        systemAndOfficialAdapter = new SystemAndOfficialAdapter(activity, listBeans, layout, type);
        recyclerList.setLayoutManager(new LinearLayoutManager(activity));
        recyclerList.setAdapter(systemAndOfficialAdapter);
        setHttpData();
    }
    //修改系统消息标记
    private void setHttpRead() {
        Log.i(TAG, "setHttpRead: ---------------");
        MeInfoService.setMsgRead(token,deviceInfo,mySeleInfo.getId()).subscribe(result -> {
            Log.i(TAG, "setHttpRead: ----------"+result.toString());
            if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){

            }
        },throwable -> {
            Log.i(TAG, "setHttpRead: ------"+throwable.toString());
            toast_MakeText(getResources().getString(R.string.net_error));
        });

    }

    /**
     * @return
     * @method
     * @description 数据请求
     * @date: 2018/11/17 14:02
     * @author: ljp
     */
    private void setHttpData() {
        if (type.equals("Official")) {//请求官方通知信息
            Log.i(TAG, "setHttpData: ----Official-----");
            MeInfoService.officialMessage(id, token, deviceInfo, page + "").subscribe(coummunityNotice -> {
                if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    Log.i(TAG, "setHttpData: ---getCount---"+coummunityNotice.getPage().toString());
                    int i = coummunityNotice.getPage().getCount() / coummunityNotice.getPage().getPageSize() +
                            (coummunityNotice.getPage().getCount() % coummunityNotice.getPage().getPageSize() == 0 ? 0 : 1);
                   // Log.i(TAG, "setHttpData: --i--"+i+"-page---"+page);
                    if (i != 0 && page > i) {//判断是否是最后一页{//判断是否是最后一页
                        smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                    } else {
                        if (page == 1) {
                            listBeans.clear();
                            smartRefresh.finishRefresh();
                        }
                        if (coummunityNotice.getPage().getList() != null) {
                            listBeans.addAll(coummunityNotice.getPage().getList());
                            systemAndOfficialAdapter.notifyDataSetChanged();
                            smartRefresh.setVisibility(View.VISIBLE);
                        } else {
                            linearLayout.setVisibility(View.VISIBLE);
                        }
                        smartRefresh.finishLoadMore();
                    }
                } else if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                    Utils.setToken(context);
                } else {
                    toast_MakeText(coummunityNotice.getMsg());
                }
            }, throwable -> {
                Log.i(TAG, "setHttpData: ----" + throwable.toString());
                toast_MakeText(getResources().getString(R.string.net_error));

            });
        } else {//请求系统消息
            MeInfoService.systemMessage(id, token, deviceInfo, page + "","").subscribe(coummunityNotice -> {
                // Log.i(TAG, "setHttpData: ----"+coummunityNotice.getPage().getList().size());
                if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    //Log.i(TAG, "setHttpData: ---getCount---"+coummunityNotice.getPage().getCount());
                    int i = coummunityNotice.getPage().getCount() / coummunityNotice.getPage().getPageSize() +
                            (coummunityNotice.getPage().getCount() % coummunityNotice.getPage().getPageSize() == 0 ? 0 : 1);
                   // Log.i(TAG, "setHttpData: --i--"+i+"-page---"+page);

                    if (i != 0 && page > i) {//判断是否是最后一页{//判断是否是最后一页
                        smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                    } else {
                        if (page == 1) {
                            listBeans.clear();
                            smartRefresh.finishRefresh();
                        }
                        if (coummunityNotice.getPage().getList() != null) {
                            listBeans.addAll(coummunityNotice.getPage().getList());
                            systemAndOfficialAdapter.notifyDataSetChanged();
                            smartRefresh.setVisibility(View.VISIBLE);
                        } else {
                            linearLayout.setVisibility(View.VISIBLE);
                        }
                        smartRefresh.finishLoadMore();
                    }
                } else if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                    Utils.setToken(context);
                } else {
                    toast_MakeText(coummunityNotice.getMsg());
                }
            }, throwable -> {
                Log.i(TAG, "setHttpData: ----" + throwable.toString());
                toast_MakeText(getResources().getString(R.string.net_error));

            });

        }
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(activity, IMessageActivity.class));
        finish();
    }

    @OnClick(R.id.linear_back)
    public void onClick() {
        startActivity(new Intent(activity, IMessageActivity.class));
        finish();
    }
}
